<template>
  <div class="list">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="关键字">
            <el-input
              clearable
              v-model="searchForm.keyword"
              placeholder="请输入关键字"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="handleAddForm">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="id" label="编号" width="180" />
        <el-table-column prop="sn" label="部门编号" width="180" />
        <el-table-column prop="name" label="部门名称" width="180" />
        <el-table-column prop="parent.name" label="父部门" width="180" />
        <el-table-column label="分配员工" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              class="el-icon-position"
              @click="handleTransfer(scope.row)"
              >分配</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              class="el-icon-edit"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              class="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" status-icon ref="editForm" label-width="80px">
        <el-form-item label="部门编号">
          <el-input v-model="editForm.sn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父部门">
          <el-select
            v-model="editForm.parent.id"
            placeholder="请选择你的父部门"
            @change="changeDepartment(departmentInfo)"
          >
            <el-option
              v-for="item in departmentInfo"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :visible.sync="transferForm.drawer"
      size="50%"
      :with-header="false"
      :before-close="handleClose"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div class="demo-drawer__content">
        <div style="text-align: center">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="transferForm.value"
            filterable
            :render-content="renderFunc"
            :titles="['所有员工', transferForm.target]"
            :button-texts="['到左边', '到右边']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}',
            }"
            @change="handleChange"
            :data="transferForm.transferData"
          >
            <el-button class="transfer-footer" slot="left-footer" size="small"
              >操作</el-button
            >
            <el-button class="transfer-footer" slot="right-footer" size="small"
              >操作</el-button
            >
          </el-transfer>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            type="primary"
            @click="$refs.drawer.closeDrawer()"
            :loading="transferForm.loading"
            >{{ transferForm.loading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  departmentList,
  saveOrUpdate,
  deleteById,
  departmentAll,
} from "@/api/department";
import { employeeAll, selectByDeptId, batchList } from "@/api/employee";
export default {
  name: "List",
  data() {
    return {
      total: 0,
      value: "",
      dialogTitle: "",
      isSwitch: true,
      dialogFormVisible: false,
      searchForm: {
        keyword: "",
        currentPage: 1,
        pageSize: 3,
      },
      tableData: [],
      departmentInfo: [],
      editForm: {
        parent: {
          id: undefined,
        },
      },
      transferForm: {
        drawer: false,
        // 目标部门
        target: "",
        // 目标部门 ID
        targetId: undefined,
        transferData: [],
        value: [],
        loading: false,
        dialog: false,
      },
      realEmpIds: [],
    };
  },
  methods: {
    fetchData(params) {
      departmentList(params).then((res) => {
        const { data } = res;
        this.total = data.totalCount;
        this.tableData = data.data;
        this.searchForm.currentPage = data.currentPage;
        this.searchForm.pageSize = data.pageSize;
      });
    },
    onSubmit() {
      this.searchForm.currentPage = 1;
      this.fetchData(this.searchForm);
    },
    handleEdit(data) {
      this.dialogFormVisible = true;
      this.dialogTitle = "部门编辑";
      if (!data.parent) {
        data.parent = {};
      }
      this.editForm = data;
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除这一条记录, 确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deleteById(row.id).then((res) => {
            console.log("@", res);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.fetchData(this.fetchData);
          });
        })
        .catch((err) => {
          console.log("Error.message: ", err);
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange(currentPage) {
      this.searchForm.currentPage = currentPage;
      this.fetchData(this.searchForm);
    },
    handleSizeChange(pageSize) {
      this.searchForm.pageSize = pageSize;
      this.fetchData(this.searchForm);
    },
    handleAddForm() {
      this.dialogFormVisible = true;
      this.dialogTitle = "部门新增";
      this.editForm = {
        parent: {},
      };
    },
    handleEditForm() {
      saveOrUpdate(this.editForm).then((res) => {
        this.fetchData(this.serachForm);
        this.$message.success("操作成功！");
        this.dialogFormVisible = false;
      });
    },
    changeDepartment(data) {
      data.forEach((element) => {
        if (element.name === this.value) {
          this.editForm.dept = element;
        }
      });
    },
    handleTransfer(row) {
      this.transferForm.drawer = true;
      this.transferForm.target = row.name;
      this.transferForm.targetId = row.id;
      this.fetchDataByDeptId(row.id);
    },
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys);
    },
    renderFunc(h, option) {
      return (
        <span>
          {option.key} - {option.label}
        </span>
      );
    },
    generateData() {
      employeeAll().then((res) => {
        let data = [];
        let temp = res.data;
        for (let i = 0; i < temp.length; i++) {
          data.push({
            key: temp[i].id,
            label: temp[i].username,
            // disabled: i % 4 === 0,
          });
        }
        this.transferForm.transferData = data;
      });
      // for (let i = 1; i <= 15; i++) {
      //   data.push({
      //     key: i,
      //     label: `备选项 ${i}`,
      //     disabled: i % 4 === 0,
      //   });
      // }
      // this.transferForm.transferData = data;
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm("确定要提交表单吗？")
        .then((_) => {
          this.loading = true;
          // console.log(this.transferForm.targetId, this.transferForm.value);
          // 管理人员在确定提交给员工分配部门的时候发送请求到后端，进行批量的给员工分配部门
          // 需要两个参数
          // 第一个参数是被分配的目标部门的一个id
          // 第二个参数是被分配的员工 id
          let empIds = Object.assign([], this.transferForm.value);

          let temp = [];
          empIds.forEach((res) => {
            let index = this.realEmpIds.indexOf(res);
            if (index == -1) {
              temp.push(res);
            }
          });
          const params = {
            deptId: this.transferForm.targetId,
            empIds: temp,
          };
          console.log(params);
          batchList(params).then((res) => {
            console.log("响应成功", res);
          });
          this.transferForm.value.length = 0;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
            }, 400);
          }, 300);
        })
        .catch((_) => {});
    },
    cancelForm() {
      this.transferForm.loading = false;
      this.transferForm.dialog = false;
      this.transferForm.drawer = false;
      clearTimeout(this.timer);
    },
    fetchDataByDeptId(deptId) {
      selectByDeptId(deptId).then((res) => {
        console.log("我是干饭部门下面的员工", res.data);
        res.data.forEach((employee) => {
          this.transferForm.value.push(employee.id);
        });
      });
      this.realEmpIds = this.transferForm.value;
      console.log("我执行了", deptId, this.transferForm.value);
    },
  },
  mounted() {
    this.fetchData();
    this.generateData();
    departmentAll().then((res) => {
      this.departmentInfo = res.data;
    });
  },
};
</script>

<style scoped>
.demo-drawer__footer {
  position: absolute;
  bottom: 20px;
  left: 5px;
}
</style>